$(function () {
    layui.use(['table', 'form', 'layer', 'laydate', 'soulTable','util'], function () {
        var table = layui.table,
            form = layui.form,
            layer = layui.layer,
            laydate = layui.laydate,
            soulTable = layui.soulTable,
            util = layui.util;
        var fixedDate = util.toDateString(new Date(), 'yyyy-MM-dd'), tbIndex = null;
        var devTypeObj = {
            1: {name: '水', unit:'T'},
            0: {name: '电', unit:'kW·h'}
        };
        initAll();

        function initAll(){
            initDate();
            getData(fixedDate);
        }

        function initDate() {
            laydate.render({
                elem: '#datetime'
                , value: new Date()
                , format: 'yyyy-MM-dd'
                , trigger: 'click'
                , done: function (value) {
                    fixedDate = value;
                    getData(fixedDate);
                }
            })
        }

        //查
        function getData(date) {
            $.ajax({
                type: "post",
                url: ctx + "/capacity/getAll.do",
                data: {
                    fixedDate: date
                },
                dataType: "json",
                success: function (data) {
                    if (data != null) {
                        renderTable(data);
                    }
                }
            });
        }

        function renderTable(data) {
            var tbHeigth = $('.settings-wrap').height();
            tbIndex = table.render({
                elem: '#capacitySet'
                , id: 'myTable'
                , height: tbHeigth
                , cellMinWidth: 80
                , data: data
                , title: '产能表'
                , toolbar: '#toolbar'
                , defaultToolbar: ['print', 'exports']
                , drag: false // 关闭拖拽列功能
                , cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: "areaName", title: "区域", filter: true},
                    {field: 'deviceTypeCode', title: '设备类型',templet: function (d) {
                            return  devTypeObj[d.deviceTypeCode].name + '表'
                        }},
                    {field: "anotherName", title: "设备", width: 300, filter: true},
                    {field: "standard", title: "标准"},
                    {field: "intervalQuantity", title: "实际用量"},
                    {field: "value", title: "产能(T)<i class='layui-icon layui-icon-about tips' title='双击产能单元格，可修改产能'></i>", edit: 'text'},
                    {field: "remark", title: "备注"},
                    // {field: "", title: ""}
                ]]
                , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                    layout: ['prev', 'page', 'next', 'count', 'skip', 'limit'] //自定义分页布局
                    , groups: 5 //只显示 5 个连续页码
                    , limit: 15
                    , limits: [15, 30, 45, 60]
                }
                , loading: true
                , filter: {
                    items: ['column', 'data'],
                    bottom: false
                }
                , done: function () {
                    $('.layui-table-view > .layui-table-box').height(tbHeigth - 41);
                    $('.layui-table-view > .layui-table-box .layui-table-body').height(tbHeigth - 80);
                    soulTable.render(this);
                }
            });
        }

        // 修改单个设备产能
        table.on('edit(capacitySet)', function (obj) {
            var field = {
                pkid: obj.data.pkid,
                fixedDate: fixedDate,
                value: obj.value,
                meterCode: obj.data.meterCode
            };
            updateCapacity(field);
        });

        // 批量编辑按钮-调用工具条中隐藏的获取选中行数据按钮
        $('.multiEditBtn').click(function(){
            $('.getCheckData').click();
        });
        $('.clearBtn').click(function(){
            $('.clearFilter').click();
        });

        table.on('toolbar(capacitySet)', function (obj) {
            if (obj.event === 'clearFilter') {
                // 清除所有筛选条件并重载表格
                // 参数: tableId
                soulTable.clearFilter('capacitySet')
            } else if (obj.event === 'checked') { // 批量
                var checkedRow = soulTable.cache['myTable'].filter(item => item.LAY_CHECKED); // 所选数据
                // console.log(checkedRow);
                var layerIdx = layer.open({
                    type: 1,
                    title: "编辑",
                    closeBtn: 1,
                    anim: 0,
                    area: 'auto',
                    content: $('#edit-tpl').html(),
                    success: function(layero){
                        layero.find('.len').text(checkedRow.length);
                    }
                });
                form.on('submit(edit-param)', function (res) {
                    for(var i=0;i<checkedRow.length;i++){
                        checkedRow[i].value = res.field.capacity;
                    }
                    // var field = {
                    //     productivitys: checkedRow
                    // };
                    // console.log(checkedRow)
                    updateBatchCapacity(checkedRow);
                    layer.close(layerIdx);
                    return false;
                });
                $(".edit-param button[type='cancel']").click(function () {
                    layer.close(layerIdx);
                    return false;
                });

            }
        });

        // 编辑单个
        function updateCapacity(data) {
            $.ajax({
                url: ctx + "/capacity/edit.do",
                type: "post",
                data: data,
                success: function (result) {
                    if (result.code == '000000') {
                        getData(fixedDate);
                    } else {
                        layer.alert(result.message);
                    }
                }
            });
        }

        // 编辑多个
        function updateBatchCapacity(data) {
            $.ajax({
                url: ctx + "/capacity/batchEdit.do",
                contentType: "application/json",
                type: "post",
                data: JSON.stringify(data),
                success: function (result) {
                    if (result.code == '000000') {
                        getData(fixedDate);
                    } else {
                        layer.alert(result.message);
                    }
                }
            });
        }

        // 导出excel
        $('.exportBtn').click(function(){
            soulTable.export('myTable',{filename: fixedDate + '产能统计表.xlsx'});
        });

        // 打印
        $('.printBtn').click(function () {
            createPrintTable();
            // 创建iframe，填入需要打印的内容和样式
            var iframe = document.createElement('IFRAME'),
                doc = null,
                style = ["<style>", "body{font-size: 12px; color: #000;}",
                    "table{width: 100%; border-collapse: collapse; border-spacing: 0;}",
                    "th,td{line-height: 20px; padding: 5px 0; border: 1px solid #000; text-align: center; font-size: 12px; color: #000;}",
                    "thead tr th:first-child,tbody tr td:first-child{width:80px}",
                    "a{color: #000; text-decoration:none;}", "*.layui-hide{display: none}", ".ptitle{font-size:16px;font-weight:bold;text-align:center;}" ,"</style>"].join(""),
                printHtml = $($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-header').html()),
                ptitle = $('<div class="ptitle">' + fixedDate + '设备产能表</div>');
            iframe.setAttribute("id", "print-iframe");
            iframe.setAttribute('style', 'position:absolute;width:100%;height:100%;left:0px;top:0px;z-index:1024;background-color:#fff;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            printHtml.append($('#printContentBox .layui-table-view > .layui-table-box > .layui-table-main').find("table").html());
            printHtml.find("th.layui-table-patch").remove();
            printHtml.find(".layui-table-col-special").remove();
            doc.write(style + ptitle.prop("outerHTML") +printHtml.prop("outerHTML"));
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
            iframe.remove();
            $('#printContentBox').empty();
        });

        function createPrintTable() {
            $('#printContentBox').html('<table id="printTb"></table>');
            var temp = tbIndex.config;
            // 所有数据加载为新表格
            table.render({
                elem: '#printTb'
                , data: temp.data
                , cellMinWidth: 48
                , size: 'sm'
                , defaultToolbar: []
                , cols: temp.cols
                , limit: temp.data.length
            })
        }
    })
});
